package webmarket.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import webmarket.common.MarkerController;
import webmarket.common.MarkerController.MarkerTypes;

@Controller
@RequestMapping("/error")
public class ErrorController extends ControllerBase {

	public static Map<ErrorTypes, String> errorMsg;
	public static boolean logError = true;

	static {
		errorMsg = new HashMap<ErrorTypes, String>();
		errorMsg.put(ErrorTypes.UserNotExists, "A megadott felhasználó nem létezik");
		errorMsg.put(ErrorTypes.NotCurrentUser, "Nem szerkesztheted ezt a felhasználót!");
	}

	public static enum ErrorTypes {
		UserNotExists, NotCurrentUser
	}

	/**
	 * Bad request
	 */
	@RequestMapping("/400")
	public String error400(HttpServletRequest request, Exception exception) {
		logger.debug(MarkerController.getMarker(MarkerTypes.BAD_REQUEST), request.getRequestURI() + "?" + request.getQueryString(), exception);
		return "error400";
	}

	/**
	 * Forbidden
	 */
	@RequestMapping("/403")
	public String error403(HttpServletRequest request) {
		logger.warn(MarkerController.getMarker(MarkerTypes.FORBIDDEN), request.getRequestURI() + "?" + request.getQueryString());
		return "error403";
	}

	/**
	 * Not found
	 */
	@RequestMapping("/404")
	public String error404(HttpServletRequest request) {
		logger.debug(MarkerController.getMarker(MarkerTypes.NOT_FOUND), request.getRequestURI() + "?" + request.getQueryString());
		return "error404";
	}

	/**
	 * Internal server error
	 */
	@RequestMapping("/500")
	public String error500(HttpServletRequest request, Exception exception, boolean logError) {
		if (logError) {
			logger.fatal(MarkerController.getMarker(MarkerTypes.INTERNAL_ERROR), request.getRequestURI() + "?" + request.getQueryString(), exception);
		} else {
			logError = true;
		}
		return "error500";
	}

	@RequestMapping("/{msgType}")
	public ModelAndView error_default(ModelMap model, @PathVariable ErrorTypes msgType) {
		model.put("msg", errorMsg.get(msgType));
		return new ModelAndView("error_msg", model);
	}
}
